"""自定义SQL解析器模块"""

from typing import Dict, Any, List, Optional
from dataclasses import asdict
from src.base import bera
from src.service.preprocess.preprocess_sql_service import SQLPreprocessService
from .models import (
    TableDefinition, ColumnDefinition, IndexDefinition,
    SQLToken, SQLTokenType, get_current_timestamp
)
from .custom_lexer import SQLLexer
from .sql_parser_base import SQLParserBase


class SQLParser:
    """SQL解析器"""

    def __init__(self, sql: str):
        """初始化SQL解析器

        Args:
            sql: SQL语句
        """
        # 预处理 SQL
        preprocessor = SQLPreprocessService()
        result = preprocessor.preprocess(sql)
        sql = result.cleaned_sql

        # 词法分析
        lexer = SQLLexer(sql)
        tokens = lexer.tokenize()

        # 过滤掉注释和空白
        self.tokens = [t for t in tokens if t.type not in [SQLTokenType.COMMENT, SQLTokenType.WHITESPACE]]
        self.pos = 0

    def parse_create_table(self) -> Dict[str, Any]:
        """解析CREATE TABLE语句"""
        try:
            bera.logger.debug("=== 开始解析CREATE TABLE语句 ===")

            # 解析CREATE TABLE
            self._expect_keyword("CREATE")
            self._expect_keyword("TABLE")

            # 解析表名
            table = TableDefinition()
            table.name = self._parse_identifier()
            bera.logger.debug(f"解析到表名: {table.name}")

            # 解析表体
            if not self._match_punctuation("("):
                raise SyntaxError("Expected opening parenthesis after table name")

            table = self._parse_table_body(table)

            # 解析表选项和注释
            self._parse_table_options_and_comment(table)

            bera.logger.debug("=== 解析结果摘要 ===")
            bera.logger.debug(f"表名: {table.name}")
            bera.logger.debug(f"表注释: '{table.comment}'")
            bera.logger.debug(f"字段数: {len(table.columns)}")
            bera.logger.debug(f"索引数: {len(table.indexes)}")
            bera.logger.debug("=== 解析完成 ===")

            return self._build_result(table)
        except Exception as e:
            bera.logger.error(f"解析失败: {str(e)}")
            raise

    def _build_result(self, table: TableDefinition) -> Dict[str, Any]:
        """构建解析结果"""
        # 获取主键列名集合
        primary_key_columns = set()
        for idx in table.indexes:
            if idx.type == "PRIMARY KEY":
                primary_key_columns.update(idx.columns)
                bera.logger.debug(f"找到主键索引: {idx.type}, 列: {idx.columns}")
                break

        # 构造字段字典
        columns_dict = {}
        for col in table.columns:
            type_info = {
                "name": col.type["name"],
                "length": col.type.get("length"),
                "precision": col.type.get("precision"),
                "scale": col.type.get("scale"),
                "display_width": col.type.get("display_width")
            }
            # 移除所有为 None 的字段
            type_info = {k: v for k, v in type_info.items() if v is not None}

            # 字段是主键的条件：
            # 1. 字段定义中有 PRIMARY KEY 标记
            # 2. 字段名在主键索引的列中
            is_primary = col.primary_key or col.name in primary_key_columns

            columns_dict[col.name] = {
                "name": col.name,
                "type": type_info,
                "nullable": col.nullable,
                "auto_increment": col.auto_increment,
                "comment": col.comment,
                "default_value": col.default_value,
                "primary_key": is_primary
            }

        # 提取主键信息
        primarykey_info = self._extract_primarykey_info(table, columns_dict)

        return {
            "metadata": {
                "version": "1.0",
                "source_file": table.name + ".sql",  # 使用表名作为源文件名
                "dialect": "mysql",
                "timestamp": get_current_timestamp()
            },
            "table": {
                "name": table.name,
                "comment": table.comment,
                "engine": table.options.get("engine"),
                "charset": table.options.get("charset"),
                "collate": table.options.get("collate"),
                "indexes": [asdict(idx) for idx in table.indexes],
                "primarykeys": primarykey_info
            },
            "columns": columns_dict
        }

    def _extract_primarykey_info(self, table: TableDefinition, columns_dict: Dict[str, Any]) -> Dict[str, Any]:
        """提取主键信息

        Args:
            table: 表定义
            columns_dict: 字段字典

        Returns:
            主键信息字典，符合设计文档格式
        """
        # 查找主键索引
        primary_key_index = None
        for idx in table.indexes:
            if idx.type == "PRIMARY KEY":
                primary_key_index = idx
                break

        # 如果没有找到主键索引，检查是否有行内主键定义
        inline_primary_keys = []
        for col_name, col_info in columns_dict.items():
            if col_info.get("primary_key", False):
                inline_primary_keys.append(col_name)

        # 确定主键字段列表
        if primary_key_index:
            primary_key_fields = primary_key_index.columns
        elif inline_primary_keys:
            primary_key_fields = inline_primary_keys
        else:
            primary_key_fields = []

        # 构建主键信息
        primarykey_count = len(primary_key_fields)
        is_composite = primarykey_count > 1
        has_auto_increment = False

        # 构建字段详细信息
        fields_info = []
        for order, field_name in enumerate(primary_key_fields, 1):
            if field_name in columns_dict:
                col_info = columns_dict[field_name]
                field_auto_increment = col_info.get("auto_increment", False)
                if field_auto_increment:
                    has_auto_increment = True

                # 获取字段类型字符串
                type_info = col_info.get("type", {})
                type_name = type_info.get("name", "")
                type_length = type_info.get("length")

                # 构建完整的类型字符串
                if type_length:
                    field_type = f"{type_name}({type_length})"
                else:
                    field_type = type_name

                fields_info.append({
                    "name": field_name,
                    "type": field_type,
                    "order": order,
                    "auto_increment": field_auto_increment,
                    "nullable": col_info.get("nullable", True)
                })

        return {
            "count": primarykey_count,
            "is_composite": is_composite,
            "has_auto_increment": has_auto_increment,
            "fields": fields_info
        }

    def _parse_table_body(self, table: TableDefinition):
        first_item = True
        primary_key_columns = []  # 用于收集行内PRIMARY KEY列
        while self.pos < len(self.tokens):
            token = self._peek_token()
            bera.logger.debug(f"当前解析token: {token.type} = {token.value}")

            # 如果遇到右括号，说明表体解析完成
            if token.type == SQLTokenType.PUNCTUATION and token.value == ")":
                bera.logger.debug("遇到右括号，表体解析完成")
                bera.logger.debug("--- 表体解析完成 ---")

                # 如果有行内主键，添加到索引列表
                if primary_key_columns:
                    bera.logger.debug(f"处理行内PRIMARY KEY: {primary_key_columns}")
                    table.indexes.append(IndexDefinition(
                        name="PRIMARY",
                        type="PRIMARY KEY",
                        columns=primary_key_columns
                    ))
                return table

            # 如果不是第一个项目，需要先匹配逗号
            if not first_item:
                bera.logger.debug("不是第一个定义项，检查逗号分隔符")
                if not self._match_punctuation(","):
                    # 如果下一个是右括号，说明是最后一个项目
                    if self._peek_token().type == SQLTokenType.PUNCTUATION and self._peek_token().value == ")":
                        bera.logger.debug("下一个是右括号，继续解析最后一项")
                        continue
                    # 如果解析失败，尝试跳过到下一个分隔符
                    bera.logger.warning("警告：逗号解析失败，尝试恢复到下一个分隔符")
                    while self.pos < len(self.tokens):
                        token = self._peek_token()
                        if token.type == SQLTokenType.PUNCTUATION and token.value in [",", ")"]:
                            break
                        self.pos += 1
                    continue

            # 解析字段或索引定义
            token = self._peek_token()
            if token.type == SQLTokenType.KEYWORD and token.value.upper() in ["PRIMARY", "UNIQUE", "INDEX", "KEY"]:
                bera.logger.debug("--> 开始解析索引定义")
                index = self._parse_index_definition()
                if index:
                    bera.logger.debug(f"成功解析到索引: {index.type} {index.name} ({', '.join(index.columns)})")
                    table.indexes.append(index)
                else:
                    bera.logger.warning("警告：索引解析失败")
            else:
                bera.logger.debug("--> 开始解析字段定义")
                column = self._parse_column_definition()
                if column:
                    bera.logger.debug(f"成功解析到字段: {column.name} {column.type}")
                    table.columns.append(column)
                    # 如果是行内PRIMARY KEY，添加到主键列列表
                    if column.primary_key:
                        primary_key_columns.append(column.name)
                else:
                    bera.logger.warning("警告：字段解析失败，尝试恢复到下一个分隔符")
                    while self.pos < len(self.tokens):
                        token = self._peek_token()
                        if token.type == SQLTokenType.PUNCTUATION and token.value in [",", ")"]:
                            break
                        self.pos += 1
                    continue

            first_item = False

        raise SyntaxError("Unexpected end of input while parsing table body")

    def _parse_column_definition(self) -> Optional[ColumnDefinition]:
        try:
            bera.logger.debug("  解析字段定义开始")
            name = self._parse_identifier()
            bera.logger.debug(f"  字段名: {name}")
            type_info = self._parse_type_definition()
            bera.logger.debug(f"  类型信息: {type_info}")

            column = ColumnDefinition(name=name, type=type_info)

            while self.pos < len(self.tokens):
                token = self._peek_token()
                bera.logger.debug(f"  处理字段属性: {token.type} = {token.value}")

                if token.type == SQLTokenType.PUNCTUATION and token.value in [",", ")"]:
                    bera.logger.debug("  字段定义结束")
                    break

                if self._match_keyword("NOT") and self._match_keyword("NULL"):
                    column.nullable = False
                    bera.logger.debug("  设置NOT NULL")
                elif self._match_keyword("AUTO_INCREMENT"):
                    column.auto_increment = True
                    bera.logger.debug("  设置AUTO_INCREMENT")
                elif self._match_keyword("PRIMARY") and self._match_keyword("KEY"):
                    column.primary_key = True
                    bera.logger.debug("  设置PRIMARY KEY")
                elif self._match_keyword("DEFAULT"):
                    column.default_value = self._parse_default_value()
                    bera.logger.debug(f"  设置DEFAULT: {column.default_value}")
                elif self._match_keyword("COMMENT"):
                    column.comment = self._parse_string_literal()
                    bera.logger.debug(f"  设置COMMENT: '{column.comment}'")
                else:
                    self.pos += 1

            return column
        except SyntaxError as e:
            bera.logger.error(f"  警告：字段解析出错 - {str(e)}")
            return None

    def _parse_index_definition(self) -> Optional[IndexDefinition]:
        bera.logger.debug("  解析索引定义开始")
        index_type = ""
        index_name = ""

        token = self._peek_token()
        bera.logger.debug(f"  当前token: {token.type} = {token.value}")

        if self._match_keyword("PRIMARY"):
            bera.logger.debug("  解析主键索引")
            self._expect_keyword("KEY")
            index_type = "PRIMARY KEY"
            index_name = "PRIMARY"
        elif self._match_keyword("UNIQUE"):
            bera.logger.debug("  解析唯一索引")
            if self._match_keyword("KEY") or self._match_keyword("INDEX"):
                index_type = "UNIQUE KEY"
            else:
                index_type = "UNIQUE KEY"
            if self._peek_token().type == SQLTokenType.IDENTIFIER:
                index_name = self._parse_identifier()
        elif self._match_keyword("KEY") or self._match_keyword("INDEX"):
            bera.logger.debug("  解析普通索引")
            index_type = "KEY"
            if self._peek_token().type == SQLTokenType.IDENTIFIER:
                index_name = self._parse_identifier()
        elif token.type == SQLTokenType.IDENTIFIER:
            bera.logger.debug(f"  解析命名索引: {token.value}")
            index_name = self._parse_identifier()
            if self._match_keyword("KEY") or self._match_keyword("INDEX"):
                index_type = "KEY"
            elif self._peek_token().type == SQLTokenType.PUNCTUATION and self._peek_token().value == "(":
                # 如果标识符后直接跟着括号，也认为是一个普通索引
                index_type = "KEY"
            else:
                bera.logger.warning("  警告：不是有效的索引定义")
                return None

        bera.logger.debug(f"  索引类型: {index_type}, 索引名: {index_name}")
        try:
            columns = self._parse_column_list()
            bera.logger.debug(f"  索引列: {columns}")

            # 根据索引名称和类型进行调整
            if index_type == "PRIMARY KEY" or index_name.upper() == "PRIMARY":
                # 主键索引强制使用PRIMARY作为名称和PRIMARY KEY作为类型
                index_name = "PRIMARY"
                index_type = "PRIMARY KEY"
            elif index_name.upper().startswith("UK_"):
                # 以UK_开头的索引设置为唯一索引
                index_type = "UNIQUE KEY"
            elif index_type == "KEY" and not index_name:
                # 如果是无名的普通索引，但是索引列中包含id，认为是主键
                if len(columns) == 1 and columns[0].lower() == "id":
                    index_name = "PRIMARY"
                    index_type = "PRIMARY KEY"

            bera.logger.debug(f"  最终索引类型: {index_type}, 索引名: {index_name}")
            return IndexDefinition(name=index_name, type=index_type, columns=columns)
        except SyntaxError as e:
            bera.logger.error(f"  警告：索引列解析失败 - {str(e)}")
            return None

    def _parse_type_definition(self) -> Dict[str, str]:
        """解析类型定义，包括类型名和可选的长度"""
        bera.logger.debug("  解析类型定义开始")
        type_info = {
            "name": "",
            "length": None,
            "precision": None,
            "scale": None,
            "display_width": None
        }
        bera.logger.debug(f"  初始化type_info: {type_info}")

        # 解析类型名
        token = self._peek_token()
        type_name = token.value.upper()
        type_info["name"] = type_name
        self.pos += 1
        bera.logger.debug(f"  设置类型名: {type_name}")

        # 解析类型长度/精度
        if self._match_punctuation("("):
            length_parts = []
            while True:
                token = self._peek_token()
                if token.type == SQLTokenType.PUNCTUATION and token.value == ")":
                    self.pos += 1
                    break
                elif token.type == SQLTokenType.PUNCTUATION and token.value == ",":
                    length_parts.append(",")
                    self.pos += 1
                else:
                    length_parts.append(token.value)
                    self.pos += 1

            # 保存原始的长度字符串
            length_str = "".join(length_parts)
            bera.logger.debug(f"  解析到长度字符串: {length_str}")

            # 解析括号内的数字
            numbers = length_str.split(",")
            if len(numbers) == 1:
                # 单个数字可能是长度、显示宽度或精度
                value = int(numbers[0])
                if type_name in ["TINYINT", "SMALLINT", "INT", "BIGINT"]:
                    type_info["display_width"] = value
                    bera.logger.debug(f"  设置显示宽度: {value}")
                elif type_name in ["FLOAT", "DOUBLE"]:
                    type_info["precision"] = value
                    bera.logger.debug(f"  设置精度: {value}")
                else:
                    type_info["length"] = value
                    bera.logger.debug(f"  设置长度: {value}")
            elif len(numbers) == 2:
                # 两个数字表示精度和小数位数
                type_info["length"] = length_str  # 保持原始格式
                type_info["precision"] = int(numbers[0])
                type_info["scale"] = int(numbers[1])
                bera.logger.debug(f"  设置精度和小数位: precision={type_info['precision']}, scale={type_info['scale']}")

        bera.logger.debug(f"  最终类型信息: {type_info}")
        return type_info

    def _parse_default_value(self) -> str:
        bera.logger.debug("    解析默认值开始")
        token = self._peek_token()

        # 处理字符串默认值
        if token.type == SQLTokenType.STRING:
            value = self._parse_string_literal()
            bera.logger.debug(f"    解析到字符串默认值: {value}")
            return value

        # 处理带括号的默认值，如 DEFAULT (CURRENT_DATE)
        if token.type == SQLTokenType.PUNCTUATION and token.value == "(":
            self.pos += 1  # 跳过左括号
            nested_value = []
            nested_level = 1

            while self.pos < len(self.tokens) and nested_level > 0:
                token = self._peek_token()
                if token.type == SQLTokenType.PUNCTUATION:
                    if token.value == "(":
                        nested_level += 1
                        nested_value.append(token.value)
                    elif token.value == ")":
                        nested_level -= 1
                        if nested_level > 0:
                            nested_value.append(token.value)
                        self.pos += 1
                        continue
                elif token.type == SQLTokenType.OPERATOR:
                    nested_value.append(f" {token.value} ")
                else:
                    nested_value.append(token.value)
                self.pos += 1

            value = f"({''.join(nested_value)})"
            bera.logger.debug(f"    解析到带括号的默认值: {value}")
            return value

        # 处理普通默认值
        value = token.value
        self.pos += 1
        bera.logger.debug(f"    解析到默认值: {value}")

        # 处理 CURRENT_TIMESTAMP(3) 和 CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
        if value == "CURRENT_TIMESTAMP":
            # 检查是否有精度参数 (3)
            next_token = self._peek_token()
            if next_token and next_token.type == SQLTokenType.PUNCTUATION and next_token.value == "(":
                self.pos += 1  # 跳过左括号
                precision_token = self._peek_token()
                if precision_token and precision_token.type == SQLTokenType.NUMBER:
                    precision = precision_token.value
                    self.pos += 1  # 跳过数字
                    right_paren = self._peek_token()
                    if right_paren and right_paren.type == SQLTokenType.PUNCTUATION and right_paren.value == ")":
                        self.pos += 1  # 跳过右括号
                        value = f"CURRENT_TIMESTAMP({precision})"
                        bera.logger.debug(f"    解析到带精度的默认值: {value}")
                    else:
                        # 如果没有找到右括号，回退
                        self.pos -= 2
                else:
                    # 如果没有找到数字，回退
                    self.pos -= 1

            # 检查是否有 ON UPDATE 子句
            next_token = self._peek_token()
            if next_token and next_token.type == SQLTokenType.IDENTIFIER and next_token.value.upper() == "ON":
                self.pos += 1  # 跳过 ON
                update_token = self._peek_token()
                if update_token and update_token.type == SQLTokenType.IDENTIFIER and update_token.value.upper() == "UPDATE":
                    self.pos += 1  # 跳过 UPDATE
                    current_token = self._peek_token()
                    if current_token and current_token.value.upper() == "CURRENT_TIMESTAMP":
                        self.pos += 1  # 跳过 CURRENT_TIMESTAMP

                        # 检查是否有精度参数 (3)
                        precision_token = self._peek_token()
                        if precision_token and precision_token.type == SQLTokenType.PUNCTUATION and precision_token.value == "(":
                            self.pos += 1  # 跳过左括号
                            precision_num = self._peek_token()
                            if precision_num and precision_num.type == SQLTokenType.NUMBER:
                                precision = precision_num.value
                                self.pos += 1  # 跳过数字
                                right_paren = self._peek_token()
                                if right_paren and right_paren.type == SQLTokenType.PUNCTUATION and right_paren.value == ")":
                                    self.pos += 1  # 跳过右括号
                                    value = f"{value} ON UPDATE CURRENT_TIMESTAMP({precision})"
                                    bera.logger.debug(f"    解析到完整的ON UPDATE默认值: {value}")
                                else:
                                    # 如果没有找到右括号，回退
                                    self.pos -= 2
                                    value = f"{value} ON UPDATE CURRENT_TIMESTAMP"
                            else:
                                # 如果没有找到数字，回退
                                self.pos -= 1
                                value = f"{value} ON UPDATE CURRENT_TIMESTAMP"
                        else:
                            value = f"{value} ON UPDATE CURRENT_TIMESTAMP"
                            bera.logger.debug(f"    解析到ON UPDATE默认值: {value}")
                    else:
                        # 如果没有找到 CURRENT_TIMESTAMP，回退
                        self.pos -= 2
                else:
                    # 如果没有找到 UPDATE，回退
                    self.pos -= 1

        return value

    def _parse_column_list(self) -> List[str]:
        bera.logger.debug("    解析列列表开始")
        columns = []
        if not self._match_punctuation("("):
            raise SyntaxError("Expected opening parenthesis")

        while True:
            token = self._peek_token()
            bera.logger.debug(f"    当前列名token: {token.type} = {token.value}")

            if token.type == SQLTokenType.PUNCTUATION and token.value == ")":
                self.pos += 1
                break

            if len(columns) > 0:
                if not self._match_punctuation(","):
                    raise SyntaxError("Expected comma between column names")
                token = self._peek_token()
                bera.logger.debug(f"    下一列名token: {token.type} = {token.value}")

            if token.type == SQLTokenType.IDENTIFIER:
                column_name = self._parse_identifier()
                # 检查是否有排序方向
                next_token = self._peek_token()
                if next_token.type == SQLTokenType.IDENTIFIER and next_token.value.upper() in ["ASC", "DESC"]:
                    # 将排序方向添加到列名中
                    column_name = f"{column_name} {next_token.value.upper()}"
                    self.pos += 1
                columns.append(column_name)
                bera.logger.debug(f"    添加列: {column_name}")
            else:
                raise SyntaxError("Expected column name")

        bera.logger.debug(f"    列列表解析完成: {columns}")
        return columns

    def _parse_identifier(self) -> str:
        token = self.tokens[self.pos]
        if token.type not in [SQLTokenType.IDENTIFIER, SQLTokenType.KEYWORD]:
            raise SyntaxError(f"Expected identifier at line {token.line}, column {token.column}")
        self.pos += 1
        return token.value

    def _parse_string_literal(self) -> str:
        token = self.tokens[self.pos]
        if token.type != SQLTokenType.STRING:
            raise SyntaxError(f"Expected string literal at line {token.line}, column {token.column}")
        self.pos += 1
        # 去除引号
        return token.value[1:-1]

    def _expect_keyword(self, keyword: str):
        token = self.tokens[self.pos]
        if token.type != SQLTokenType.KEYWORD or token.value.upper() != keyword.upper():
            raise SyntaxError(f"Expected keyword {keyword} at line {token.line}, column {token.column}")
        self.pos += 1

    def _expect_punctuation(self, punct: str):
        token = self.tokens[self.pos]
        if token.type != SQLTokenType.PUNCTUATION or token.value != punct:
            raise SyntaxError(f"Expected punctuation {punct} at line {token.line}, column {token.column}")
        self.pos += 1

    def _match_keyword(self, keyword: str) -> bool:
        token = self._peek_token()
        if token.type == SQLTokenType.KEYWORD and token.value.upper() == keyword.upper():
            self.pos += 1
            return True
        return False

    def _match_punctuation(self, punct: str) -> bool:
        token = self._peek_token()
        if token.type == SQLTokenType.PUNCTUATION and token.value == punct:
            self.pos += 1
            return True
        return False

    def _peek_token(self) -> SQLToken:
        if self.pos >= len(self.tokens):
            raise SyntaxError("Unexpected end of input")
        return self.tokens[self.pos]

    def _parse_table_option(self, option_name: str) -> str:
        """通用的表选项解析"""
        bera.logger.debug(f"开始解析{option_name}选项")

        # 跳过等号(如果有)
        if self._peek_token().type == SQLTokenType.OPERATOR and self._peek_token().value == "=":
            self.pos += 1
            bera.logger.debug("跳过等号")

        # 解析选项值
        token = self._peek_token()
        if token.type in [SQLTokenType.IDENTIFIER, SQLTokenType.STRING]:
            value = self._parse_identifier() if token.type == SQLTokenType.IDENTIFIER else self._parse_string_literal()
            bera.logger.debug(f"解析到{option_name}值: {value}")
            return value

        bera.logger.warning(f"警告：{option_name}后未找到有效的值")
        return None

    def _handle_table_option(self, option_name: str, option_key: str = None, table: TableDefinition = None):
        """处理单个表选项

        Args:
            option_name: 选项名称(用于解析)
            option_key: 选项键名(用于存储,如果为None则使用option_name的小写形式)
            table: 表定义对象
        """
        value = self._parse_table_option(option_name)
        if value:
            key = option_key or option_name.lower()
            if table and hasattr(table, 'options'):
                table.options[key] = value
                bera.logger.debug(f"设置{option_name}: {value}, 当前options: {table.options}")
            else:
                bera.logger.warning(f"无法设置{option_name}: table对象无效或没有options属性")

    def _parse_table_options_and_comment(self, table: TableDefinition):
        """解析表选项和注释"""
        bera.logger.debug("--- 开始解析表选项和注释 ---")
        bera.logger.debug(f"当前table.options: {table.options}")

        while self.pos < len(self.tokens):
            token = self._peek_token()
            bera.logger.debug(f"当前处理token: {token.type} = {token.value}")

            if token.type == SQLTokenType.PUNCTUATION and token.value == ";":
                self.pos += 1
                bera.logger.debug(f"解析完成后的table.options: {table.options}")
                bera.logger.debug("--- 表选项和注释解析完成 ---")
                return

            # 处理DEFAULT关键字
            if self._match_keyword("DEFAULT"):
                bera.logger.debug("跳过DEFAULT关键字")
                continue

            # 处理CHARACTER SET
            if self._match_keyword("CHARACTER"):
                if self._match_keyword("SET"):
                    self._handle_table_option("CHARSET", "charset", table)
                continue

            # 根据token类型和值进行处理
            option_handled = False
            if token.type == SQLTokenType.KEYWORD:
                # 处理关键字形式的选项
                option_map = {
                    "ENGINE": "engine",
                    "CHARSET": "charset",
                    "COLLATE": "collate",
                    "COMMENT": "comment"
                }
                upper_value = token.value.upper()
                if upper_value in option_map:
                    self.pos += 1  # 跳过选项名称
                    self._handle_table_option(upper_value, option_map[upper_value], table)
                    if upper_value == "COMMENT":
                        table.comment = table.options["comment"]
                    option_handled = True
            elif token.type == SQLTokenType.IDENTIFIER:
                # 处理标识符形式的选项
                identifier_map = {
                    "COLLATE": "collate",
                    "ROW_FORMAT": "row_format",
                    "AUTO_INCREMENT": "auto_increment"
                }
                upper_value = token.value.upper()
                if upper_value in identifier_map:
                    self.pos += 1  # 跳过选项名称
                    self._handle_table_option(upper_value, identifier_map[upper_value], table)
                    option_handled = True

            # 如果没有处理过该token,跳过它
            if not option_handled:
                bera.logger.debug(f"跳过token: {token.type} = {token.value}")
                self.pos += 1

class CustomSQLParser(SQLParserBase):
    """自定义SQL解析器"""

    def _parse_sql(self, sql: str) -> Dict[str, Any]:
        """解析SQL语句

        Args:
            sql: SQL语句

        Returns:
            解析结果字典
        """
        parser = SQLParser(sql)
        return parser.parse_create_table()

    def parse_file(self, file_path: str) -> Dict[str, Any]:
        """解析SQL文件

        Args:
            file_path: SQL文件路径

        Returns:
            解析结果字典
        """
        with open(file_path, 'r', encoding='utf-8') as f:
            sql = f.read()
        return self.parse_sql(sql)
